$(function() {
  class Sticky {
    constructor() {
      this.init();
    }
    init() {
      this.id = cookie('id') ? cookie('id') : null;
      this.token = cookie('token') ? cookie('token') : null;
      this.initDom();
      this.ifRenderNickname();
      this.sticky_header_nav_height = this.sticky_header_nav.outerHeight();
      this.bindEvent();
    }
    initDom() {
      this.sticky_header_nav = $('#sticky-header');
      this.header_nav = $('#header');
      this.user_info_box = $('#header .user-info');
      this.pleasetoLogin = $('#header .login-tip');
      //注销按钮
      this.logout = $('#header #logout');
      //修改个人信息按钮
      this.update_userinfo = $('#header #update-userinfo');
      //修改密码
      this.update_password = $('#header #update-password');
    }
    bindEvent() {
      $(document).on('scroll', () => {
        if(600 <= $(document).scrollTop()) {
          this.sticky_header_nav.css({
            top: 0,
            boxShadow: "0 0 5px rgba(0,0,0,.5)"
          });
        }else {
          this.sticky_header_nav.css({
            top: `-${this.sticky_header_nav_height}px`,
            boxShadow: "none"
          });
        }
      });
      this.logout.on('click', async() => {
        let res = await this.sendLogout();
        if(res.data.code === 1) {
          new Toast({
            message: '用户已注销',
            color: '#E6A23C',
            callback() {
              cookie('id', null);
              cookie('token', null);
              location.reload();
            }
          });
        }
      });
      this.update_userinfo.on('click', () => {
        location.href = './updateUserInfo.html';
      });
      this.update_password.on('click', () => {
        location.href = './updatePassword.html';
      });
    }
    //判断用户是否登陆，渲染 请登录，或用户昵称
    async ifRenderNickname() {
      if(this.token) {
        this.user_info_box.css('display', 'block');
        this.pleasetoLogin.css('display', 'none');
        let res = await this.getUserInfo();
        this.user_info_box.find('.nick-text').text(res.data.info.nickname)
      }else {
        this.user_info_box.css('display', 'none');
        this.pleasetoLogin.css('display', 'block');
      }
    }
    //请求用户信息
    getUserInfo() {
      return axios({
        url: `http://127.0.0.1:8888/users/info/${this.id}`,
        headers: {
          Authorization: this.token
        }
      });
    }
    //注销用户请求
    sendLogout() {
      return axios({
        url: `http://127.0.0.1:8888/users/logout/${this.id}`,
        headers: {
          Authorization: this.token
        }
      });
    }
  }
  new Sticky();
});